package com.ruoyi.common.utils.aliyun;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.ruoyi.framework.config.AliYunConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

public class OSSUtil {
    private static final Logger logger = LoggerFactory.getLogger(OSSUtil.class);

    /**
     * 上传图片
     *
     * @param fileName 文件名
     * @param inputStream 流
     */
    public static String uploadImageToOSS(AliYunConfig aliYunConfig, String fileName, InputStream inputStream) {
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String key = aliYunConfig.getOssUrl();
        String bucketName = aliYunConfig.getOssBucketName();

        // 设置网络参数
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000);// socket超时，默认15秒
        conf.setMaxErrorRetry(2);// 失败后最大重试次数
        /**
         * 创建OSS客户端
         */
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret,conf);
        try {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//            String[] names = fileName.split("[.]");
//            String name = uuid + "." + names[names.length - 1];
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            ossClient.putObject(new PutObjectRequest(bucketName, fileName, inputStream, objectMetadata));
            return key + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    public static String uploadImageToOSS(AliYunConfig aliYunConfig, String fileName, byte[] content) {
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String key = aliYunConfig.getOssUrl();
        String bucketName = aliYunConfig.getOssBucketName();

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(content),objectMetadata);
            return key + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 上传视频
     * @param fileName
     * @param inputStream
     * @return
     */
    public static String uploadVideoToOSS(AliYunConfig aliYunConfig, String fileName, InputStream inputStream) {
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String key = aliYunConfig.getOssUrl();
        String bucketName = aliYunConfig.getOssBucketName();
        /**
         * 创建OSS客户端
         */
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            String videoType = getcontentType(fileName.substring(fileName.lastIndexOf(".")));
            if(!"image/jpg".equals(videoType)){
                objectMetadata.setContentType(videoType);
            }
            ossClient.putObject(new PutObjectRequest(bucketName, fileName, inputStream, objectMetadata));
            return key + fileName;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 多图上传
     */
    public static String[] uploadImageToOSS(AliYunConfig aliYunConfig, String[] fileNames, InputStream[] inputStreams) {
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String key = aliYunConfig.getOssUrl();
        String bucketName = aliYunConfig.getOssBucketName();
        String folder = aliYunConfig.getOssFolder()+"/";
        /**
         * 创建OSS客户端
         */
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            ConcurrentLinkedQueue concurrentLinkedQueue = new ConcurrentLinkedQueue(
                    Arrays.asList(fileNames));
            ConcurrentLinkedQueue<InputStream> streamConcurrentLinkedQueue = new ConcurrentLinkedQueue<>(
                    Arrays.asList(inputStreams));
            Iterator<InputStream> inputStreamss = streamConcurrentLinkedQueue.iterator();
            ConcurrentLinkedQueue c = new ConcurrentLinkedQueue();
            for (Iterator<String> iterator = concurrentLinkedQueue.iterator();
                 iterator.hasNext() && inputStreamss.hasNext(); ) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String[] names = iterator.next().split("[.]");
                String name = uuid + "." + names[names.length - 1];
                ossClient.putObject(new PutObjectRequest(bucketName, folder + name, inputStreamss.next()));
                c.add(key + folder + name);
            }
            return (String[]) c.toArray(new String[0]);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println(e.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return null;
    }


    /**
     * 删除图片 警告：在没有调用其他方法的情况下，请调用closeClient方法
     *
     * @param url URL全路径
     */
    public static void deleteImg(AliYunConfig aliYunConfig, String url) {
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String bucketName = aliYunConfig.getOssBucketName();
        String folder = aliYunConfig.getOssFolder()+"/";

        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        if (url == null || "".equals(url)) {
            return;
        }
        String[] paths = url.split("[.]");
        /**
         * 文件夹是否存在
         */
        if (!ossClient.doesObjectExist(bucketName, folder)) {
            ossClient.putObject(bucketName, folder, new ByteArrayInputStream(new byte[0]));
        }
        String[] name = paths[paths.length - 2].split("[/]");
        /**
         * 对象是否存在
         */
        if (ossClient
                .doesObjectExist(bucketName,
                        folder + name[name.length - 1] + "." + paths[paths.length - 1])) {
            /**
             * 删除存在对象
             */
            ossClient
                    .deleteObject(bucketName, folder + name[name.length - 1] + "." + paths[paths.length - 1]);
        }
        ossClient.shutdown();
    }

    public static void deleteFile(AliYunConfig aliYunConfig, String objectName){
        String endpoint = aliYunConfig.getOssEndpoint();
        String accessKeyId = aliYunConfig.getAccessKeyId();
        String accessKeySecret = aliYunConfig.getAccessKeySecret();
        String bucketName = aliYunConfig.getOssBucketName();
         // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 删除文件。
        ossClient.deleteObject(bucketName, objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".pdf")) {
            return "application/pdf";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp4")) {
            return "video/mpeg4";
        }
        return "image/jpg";
    }


    public static void main(String[] args) throws Exception{
//        InputStream is = new BufferedInputStream(new FileInputStream("C://Users//guwei//Desktop//6fb71204960b5d35f00f2b9029059cb2.mp4"));
//        String s = OSSUtil.uploadVideoToOSS("video13254.mp4",is);
//        System.out.println(s);
        AliYunConfig aliYunConfig = new AliYunConfig();
        OSSUtil.deleteFile(aliYunConfig,"weight/2020/video/07/wx3202010001/232c51f77a5b4f57a0ba64b708010cd5.mp4");
    }
}
